package com.lza.security;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lza.phone.entity.User;
import com.lza.phone.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//代表这是一个spring的配置类相当于Spring.xml配置文件
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;
    @Autowired
    private RestAuthorizationEntryPoint restAuthorizationEntryPoint;
    @Autowired
    private RestFulAccessDeniedHandler restFulAccessDeniedHandler;
    @Autowired
    private LogoutHandler logoutHandler;
    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

 @Override
    @Bean
    public UserDetailsService userDetailsService(){
        return username->{
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("username", username);
            User admin = userService.getOne(queryWrapper);
            if(null!=admin){
                //System.out.println("这波在security的配置文件"+admin);
                return  admin;
            }
            return  null;
        };
    }

/*
走自己的登陆逻辑
 */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return  new JwtAuthenticationTokenFilter();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //使用jwt，不需要csrf
        http.csrf().
                disable()
                //基于token，不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //允许登录访问
                .antMatchers("/login","/phone/allPhone","swagger/**",
                        "/swagger-ui.html","swagger-ui.html","/webjars/**",
                        "/swagger-ui.html/*","/swagger-resources","/swagger-resources/**","/v2/**","/doc.html/**")//可以显示所有手机，但进行操作时要授权
                .permitAll()
                //除了上面的都要求拦截认证
                .anyRequest()
                .authenticated()
                .and()
                //禁用缓存
                .headers()
                .cacheControl();
        //注销
        http.logout()
                .permitAll()
                .addLogoutHandler(logoutHandler)
                .logoutSuccessHandler(logoutSuccessHandler)
                //登出之后删除cookie
                .deleteCookies("JSESSIONID");

       //添加jwt 登录授权过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和没登录返回结果
        http.exceptionHandling()
                .accessDeniedHandler(restFulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthorizationEntryPoint);
    }

}
